import { Provide } from '@midwayjs/core';
import { Announcement } from '../entity/announcement.entity';
import { AnnouncementCommon, AnnouncementEdit, AnnouncementId, Pagination } from '../model';
import dayjs = require('dayjs');

@Provide()
export class AnnouncementService {
  async getList(req: Pagination) {
    const { count, rows }  = await Announcement.findAndCountAll({
      limit: req.pageSize,
      offset: (req.pageNo - 1) * req.pageSize,
      // attributes: { exclude: ['createdAt'] },
      order:[['id','DESC']]
    });
    const list = JSON.parse(JSON.stringify(rows)) as Announcement[]
    list.map(item => {
      item.createdAt = dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss')
    })
    return {
      count,
      rows:list,
    };
  }

  async addItem(req: AnnouncementCommon) {
    const result = await Announcement.create({
      title: req.title,
      content: req.content,
      creatorName:'物业办'
    });
    return result;
  }

  async editItem(req: AnnouncementEdit) {
    const result = await Announcement.update(
      {
        title: req.title,
        content: req.content,
      },
      {
        where: {
          id: req.id,
        },
      }
    );
    return result;
  }

  async delItem(req: AnnouncementId) {
    const result = await Announcement.destroy({
      where: {
        id: req.id,
      },
    });
    return result;
  }

  async byIdItem(req: AnnouncementId) {
    const result = await Announcement.findOne({
      where: {
        id: req.id,
      },
      attributes:{exclude:['createdAt']}
    });
    return result;
  }
}
